<template>
  <q-dialog v-model="visible">
    <q-card style="max-width: 90vw; max-height: calc(100vh - 2rem)">
      <q-card-section class="flex q-gutter-x-sm items-center">
        <modify-action
          ref="newAction"
          :priority="actions.length + 1"
          :plan="plan"
          @refresh="getActions"
          :device="plan.device"
        />
        <modify-action
          modify
          ref="modifyAction"
          @refresh="getActions"
          :device="plan.device"
        />
        <div class="text-h6">
          {{ panel === "actions" ? "管理作业动作" : "修改作业方案" }}
        </div>
        <q-space />
        <template v-if="panel === 'actions'">
          <template v-if="$q.screen.gt.xs">
            <q-btn
              color="primary"
              label="增加动作"
              icon="playlist_add"
              @click="newAction.show()"
            />
            <q-btn
              color="accent"
              label="执行一次"
              icon="check"
              @click="execute(1)"
            />
          </template>
          <template v-else>
            <q-btn
              round
              color="primary"
              icon="playlist_add"
              @click="newAction.show()"
            />
            <q-btn round color="accent" icon="check" @click="execute(1)" />
          </template>
        </template>
      </q-card-section>
      <q-separator />
      <q-tab-panels
        v-model="panel"
        animated
        infinite
        class="overflow-x-hidden"
        style="max-height: calc(100vh - 10rem); overflow-y: auto"
      >
        <q-tab-panel name="actions" class="q-pa-none">
          <q-table
            class="sticky-header-table no-border-radius"
            style="min-height: 10rem; max-height: calc(100vh - 10rem)"
            :rows="actions"
            :columns="columns"
            :visible-columns="visibleColumns"
            virtual-scroll
            :rows-per-page-options="[0]"
            :virtual-scroll-sticky-size-start="48"
            hide-bottom
            row-key="id"
          >
            <template v-slot:body="props">
              <q-tr :props="props" @click="modifyAction.show(props.row)">
                <q-td v-bind:key="'priority'" :props="props">
                  {{ props.row.priority }}
                </q-td>
                <q-td v-bind:key="'device'" :props="props">
                  {{ props.row.device }}
                </q-td>
                <q-td v-bind:key="'actionGroup'" :props="props">
                  {{
                    groupName[props.row.actionGroup] || props.row.actionGroup
                  }}
                </q-td>
                <q-td v-bind:key="'type'" :props="props">
                  {{ typeName[props.row.type] || props.row.type }}
                </q-td>
                <q-td v-bind:key="'content'" :props="props">
                  <map-pose-td
                    v-if="
                      (['lift-in', 'lift-out'].includes(props.row.type) &&
                        props.row.actionGroup === 'transport-lift') ||
                      props.row.type.includes('load')
                    "
                    label="工位点"
                    :pose-id="props.row.data.poseID"
                    map-name
                  />
                  <map-pose-td
                    v-else-if="
                      props.row.actionGroup === 'amr' &&
                      ['lift-in', 'lift-exit'].includes(props.row.type)
                    "
                    label="工位点"
                    :pose-id="props.row.data"
                    map-name
                  />
                  <map-pose-td
                    v-else-if="props.row.type.includes('move')"
                    label="点位名称"
                    :pose-id="props.row.data"
                    map-name
                  />
                  <map-pose-td
                    v-else-if="props.row.type === 'detach'"
                    label="点位名称"
                    :pose-id="props.row.data"
                    map-name
                  />
                  <div v-else-if="props.row.type === 'posture'">
                    <posture-td :id="props.row.data.split(',')[0]" />
                    {{
                      props.row.data.split(",")[1] === "joint" ? "关节" : "直线"
                    }}
                  </div>
                  <div v-else-if="props.row.type === 'attach'">
                    <map-pose-td
                      label="点位名称"
                      :pose-id="props.row.data.split(',')[0]"
                      map-name
                    />
                    {{
                      props.row.data.split(",")[2] === "FRONT" ? "车头" : "车尾"
                    }}
                  </div>
                  <div v-else-if="props.row.type === 'operate'">
                    <map-pose-td
                      label="点位名称"
                      :pose-id="props.row.data.split(',')[0]"
                      map-name
                    />
                    {{
                      props.row.data.split(",")[1] === "LOAD" ? "取料" : "放料"
                    }}
                    -
                    {{
                      props.row.data.split(",")[2] === "FRONT" ? "车头" : "车尾"
                    }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </q-table>
        </q-tab-panel>

        <q-tab-panel name="modify">
          <div class="q-gutter-y-sm">
            <q-input v-model="plan.name" outlined label="计划名称" />
            <q-select
              outlined
              v-model="plan.type"
              :options="planTypes"
              behavior="menu"
              label="方案类型"
              emit-value
              map-options
            />
            <q-slide-transition>
              <q-select
                v-if="plan.type === 'single'"
                outlined
                behavior="menu"
                v-model="plan.device"
                :options="options"
                clearable
                @filter="filterFn"
                :use-input="!plan.device"
                label="执行设备"
              />
            </q-slide-transition>
            <q-input
              rows="3"
              v-model="plan.description"
              outlined
              type="textarea"
              placeholder="在此输入对于计划的一些描述"
            />
            <q-input v-model="loop" outlined type="number" label="执行多轮">
              <template v-slot:append>
                <q-btn
                  :disable="loop < 1"
                  color="accent"
                  label="执行"
                  icon="check"
                  @click="execute(loop)"
                />
              </template>
            </q-input>
            <transition-flip>
              <q-btn
                v-if="changed"
                class="full-width text-subtitle1 text-bold"
                color="primary"
                label="修改方案"
                @click="modify"
              />
              <q-btn
                v-else
                class="full-width text-subtitle1 text-bold"
                @click="remove"
                color="negative"
                label="删除方案"
              />
            </transition-flip>
          </div>
        </q-tab-panel>
      </q-tab-panels>
      <q-tabs
        v-model="panel"
        dense
        class="bg-grey-3"
        align="justify"
        narrow-indicator
      >
        <q-tab name="actions" label="动作列表" />
        <q-tab name="modify" label="方案信息" />
      </q-tabs>
    </q-card>
  </q-dialog>
</template>

<script>
import { ref, computed, inject } from "vue";
import { api } from "boot/axios";
import { useQuasar } from "quasar";
import { useAPIStore } from "stores/api/index.js";

import ModifyAction from "components/actionPlan/ModifyAction.vue";
import TransitionFlip from "components/animations/Flip.vue";
import MapPoseTd from "components/actionPlan/MapPoseTd.vue";
import PostureTd from "components/actionPlan/PostureTd.vue";

const columns = [
  {
    name: "priority",
    label: "优先度",
    field: "priority",
    align: "center",
  },
  {
    name: "device",
    label: "执行设备",
    field: "device",
    align: "left",
  },
  {
    name: "actionGroup",
    label: "分组",
    field: "actionGroup",
    align: "left",
  },
  {
    name: "type",
    label: "类型",
    field: "type",
    align: "center",
  },
  {
    name: "content",
    label: "指令内容",
    field: "content",
    align: "center",
  },
];

export default {
  name: "ModifyPlan",
  components: {
    PostureTd,
    MapPoseTd,
    TransitionFlip,
    ModifyAction,
  },
  setup() {
    const $q = useQuasar();
    const visible = ref(false);
    const plan = ref({
      name: "",
      type: "",
      description: "",
      device: "",
    });
    const originPlan = ref({});
    const actions = ref([]);
    const options = ref([]);

    function getActions() {
      api
        .get(useAPIStore().centerUrl + "action/planID/" + plan.value.id)
        .then((rs) => {
          actions.value = rs.data;
        });
    }

    const amrConfigs = ref([]);

    function getDevices() {
      api.get(useAPIStore().centerUrl + "configs/all").then((rs) => {
        amrConfigs.value = rs.data.map((item) => {
          return item.id;
        });
      });
    }

    const typeName = {};
    const groupName = {};
    inject("typeOptions").forEach((item) => {
      typeName[item.value] = item.label;
    });
    inject("groupOptions").forEach((item) => {
      groupName[item.value] = item.label;
    });

    const getPlans = inject("getPlans");
    const loop = ref(0);
    return {
      columns,
      typeName,
      groupName,
      plan,
      amrConfigs,
      visible,
      actions,
      panel: ref("actions"),
      newAction: ref(),
      modifyAction: ref(),
      visibleColumns: computed(() => [
        "priority",
        plan.value.type === "multiple" ? "device" : null,
        "actionGroup",
        "type",
        "content",
      ]),
      planTypes: [
        {
          label: "多机调度",
          value: "multiple",
        },
        {
          label: "单机任务",
          value: "single",
        },
      ],
      options,
      show(data) {
        plan.value = JSON.parse(JSON.stringify(data));
        originPlan.value = data;
        visible.value = true;
        getActions();
        getDevices();
      },
      getActions,
      changed: computed(
        () => JSON.stringify(plan.value) !== JSON.stringify(originPlan.value)
      ),
      modify() {
        if (plan.value.type === "multiple") {
          plan.value.device = null;
        }
        api.put(useAPIStore().centerUrl + "plan", plan.value).then(() => {
          $q.notify({
            message: "方案修改成功",
            type: "positive",
          });
          getPlans();
        });
      },
      remove() {
        $q.dialog({
          title: "删除方案",
          message: "是否要删除该方案？",
          cancel: true,
          persistent: true,
        }).onOk(() => {
          api
            .delete(useAPIStore().centerUrl + "plan/" + plan.value.id)
            .then(() => {
              getPlans();
              $q.notify({
                message: "方案删除成功",
                type: "positive",
              });
              visible.value = false;
            });
        });
      },
      loop,
      execute(count) {
        $q.dialog({
          title: "执行方案",
          message: "是否要执行该方案" + count + "轮？",
          cancel: true,
          persistent: true,
        }).onOk(() => {
          api
            .get(
              useAPIStore().centerUrl +
                "action/execute/" +
                count +
                "/" +
                plan.value.id
            )
            .then((rs) => {
              if (rs.data === "done") {
                $q.notify({
                  message: "任务下发成功",
                  type: "positive",
                });
              } else {
                $q.notify({
                  message: rs.data,
                  type: "negative",
                });
              }
            });
        });
      },
      filterFn(val, update) {
        if (val === "") {
          update(() => {
            options.value = amrConfigs.value;
          });
          return;
        }

        update(() => {
          const needle = val.toLowerCase();
          options.value = amrConfigs.value.filter(
            (v) => v.toLowerCase().indexOf(needle) > -1
          );
        });
      },
    };
  },
};
</script>
